import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ldyxiangmu/bean/category_child_opt_bean.dart';
import 'package:ldyxiangmu/bean/category_goods_bean.dart';
import 'package:ldyxiangmu/bean/category_parent_opt_bean.dart';
import 'package:ldyxiangmu/provide/child_category.dart';
import 'package:ldyxiangmu/router/application.dart';
import 'package:ldyxiangmu/service/service_method.dart';
import 'package:provide/provide.dart';

class CategoryPage extends StatefulWidget {
  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  List<CategoryParentBean> parentList;
  List<CategoryChildBean> childList;
  var listIndex = 0;

  @override
  void initState() {
    _getCategoryChild(14);

    super.initState();
  }

  //获取一级分类数据源
  Future _getParentCategory() async {
    await request('categoryGoodsOpt', {'parent_opt_id': 0}).then((value) =>
        parentList = CategoryParentResult.fromJson(value)
            .entity
            .goods_opt_get_response
            .goods_opt_list);
    return parentList;
  }

  //获取二级分类数据源
  void _getCategoryChild(optId) async {
    await request('categoryGoodsOpt', {'parent_opt_id': optId}).then(
        (value) => childList = CategoryChildResult.fromJson(value).entity);
    //获取到数据源之后,如果使用有状态的控件,则需要使用setState方法来重新刷新页面(类似刷新适配器)
    //使用Provide后,则需要存入到Provide中
    Provide.value<ChildCategory>(context).setChildCategory(childList);
    _getCategoryGoodsList(
        1, Provide.value<ChildCategory>(context).childCategoryList[0].opt_id);
    Provide.value<ChildCategory>(context).changeChildIndex(0);
  }

  //获取三级列表的数据源
  void _getCategoryGoodsList(page, optId) async {
    var formData = {'page': page, 'opt_id': optId};
    await request('categoryGoodsList', formData).then((value) =>
        // print(value));
        Provide.value<ChildCategory>(context).setCategoryGoodsList(
            CategoryGoodsResult.fromJson(value)
                .entity
                .goods_search_response
                .goods_list));
  }

  //一级分类的item
  Widget _leftInkWell(index) {
    bool isClick = false;
    isClick = (index == listIndex) ? true : false;
    return InkWell(
      onTap: () {
        setState(() {
          listIndex = index;
        });
        _getCategoryChild(parentList[index].opt_id);
        Provide.value<ChildCategory>(context).rePage();
      },
      child: Container(
        height: ScreenUtil().setHeight(100),
        decoration: BoxDecoration(
            color: isClick ? Colors.black26 : Colors.white,
            border:
                Border(bottom: BorderSide(width: 1, color: Colors.black12))),
        child: Center(
          child: Text(
            parentList[index].opt_name,
            style: TextStyle(
              fontSize: ScreenUtil().setSp(28),
            ),
          ),
        ),
      ),
    );
  }

  Widget _leftCategoryNav() {
    return Container(
      width: ScreenUtil().setWidth(180),
      decoration: BoxDecoration(
          border: Border(right: BorderSide(width: 1.0, color: Colors.black12))),
      child: ListView.builder(
          itemCount: parentList.length,
          itemBuilder: (context, index) {
            return _leftInkWell(index);
          }),
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, height: 1334, width: 750);
    return Scaffold(
      appBar: AppBar(
        title: Text('分类'),
      ),
      body: Container(
        child: Row(
          children: <Widget>[
            FutureBuilder(
              future: _getParentCategory(),
              builder: (context, val) {
                if (val.hasData) {
                  return _leftCategoryNav();
                } else {
                  return Center(
                    child: Text('加载中'),
                  );
                }
              },
            ),
            Column(
              children: <Widget>[
                //右侧上方小导航,
                RightCategoryNav(),
                //右侧下方具体商品列表
                CategoryGoodsList(),
              ],
            )
          ],
        ),
      ),
    );
  }
}

class RightCategoryNav extends StatelessWidget {
  void _getCategoryGoodsList(page, optId, context) async {
    var formData = {'page': page, 'opt_id': optId};
    await request('categoryGoodsList', formData).then((value) =>
        Provide.value<ChildCategory>(context).setCategoryGoodsList(
            CategoryGoodsResult.fromJson(value)
                .entity
                .goods_search_response
                .goods_list));
  }

  @override
  Widget build(BuildContext context) {
    // List list = ['雪花', '青岛', '燕京'];
    return Provide<ChildCategory>(
      builder: (context, child, childCategory) {
        return Container(
          height: ScreenUtil().setHeight(80),
          width: ScreenUtil().setWidth(570),
          decoration: BoxDecoration(
              color: Colors.white,
              border: Border(
                  bottom: BorderSide(width: 1.0, color: Colors.black12))),
          child: ListView.builder(
            itemBuilder: (context, index) {
              return _rightInkWell(
                  childCategory.childCategoryList[index], context, index);
            },
            itemCount: childCategory.childCategoryList.length,
            scrollDirection: Axis.horizontal,
          ),
        );
      },
    );
  }

  //右侧上方导航的item
  Widget _rightInkWell(CategoryChildBean item, context, int index) {
    bool isClick = false;
    isClick = (index == Provide.value<ChildCategory>(context).childIndex)
        ? true
        : false;
    return InkWell(
      onTap: () {
        print(index.toString());
        print(Provide.value<ChildCategory>(context).childIndex.toString());
        _getCategoryGoodsList(1, item.opt_id, context);
        Provide.value<ChildCategory>(context).setOptId(item.opt_id);
        Provide.value<ChildCategory>(context).rePage();
        Provide.value<ChildCategory>(context).changeChildIndex(index);
      },
      child: Container(
        color: isClick ? Colors.pink : Colors.white,
        padding: EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 10.0),
        child: Text(
          item.opt_name,
          style: TextStyle(fontSize: ScreenUtil().setSp(28)),
        ),
      ),
    );
  }
}

class CategoryGoodsList extends StatelessWidget {
  //获取三级列表的数据源
  void _getCategoryGoodsList(page, optId, context) async {
    var formData = {'page': page, 'opt_id': optId};
    await request('categoryGoodsList', formData).then((value) =>
        // print(value));
        Provide.value<ChildCategory>(context).addCategoryGoodsList(
            CategoryGoodsResult.fromJson(value)
                .entity
                .goods_search_response
                .goods_list));
  }

  //商品图片
  Widget _goodsImage(index, context) {
    return Container(
      width: ScreenUtil().setWidth(200),
      child: Image.network(Provide.value<ChildCategory>(context)
          .categoryGoodsList[index]
          .goods_thumbnail_url),
    );
  }

  //商品名称
  Widget _goodsName(index, context) {
    return Container(
      width: ScreenUtil().setWidth(370),
      padding: EdgeInsets.all(5.0),
      child: Text(
        Provide.value<ChildCategory>(context)
            .categoryGoodsList[index]
            .goods_name,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: ScreenUtil().setSp(28)),
      ),
    );
  }

  //商品价格
  Widget _goodsPrice(index, context) {
    return Container(
      margin: EdgeInsets.only(top: 20.0),
      width: ScreenUtil().setWidth(370),
      child: Row(
        children: <Widget>[
          Text(
            '价格:¥${Provide.value<ChildCategory>(context).categoryGoodsList[index].min_group_price / 100}元',
            style: TextStyle(
                color: Colors.pink, fontSize: ScreenUtil().setSp(24.0)),
          ),
          Text(
            '原价:¥${Provide.value<ChildCategory>(context).categoryGoodsList[index].min_group_price / 100}元',
            style: TextStyle(
                color: Colors.black26,
                decoration: TextDecoration.lineThrough,
                fontSize: ScreenUtil().setSp(24.0)),
          )
        ],
      ),
    );
  }

  //构建商品的Item
  Widget _listWidgetItem(index, context) {
    return InkWell(
      onTap: () {
        Application.router.navigateTo(context,
            '/detail?id=${Provide.value<ChildCategory>(context).categoryGoodsList[index].goods_id}');
      },
      child: Container(
        padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
        decoration: BoxDecoration(
            color: Colors.white,
            border:
                Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
        child: Row(
          children: <Widget>[
            _goodsImage(index, context),
            Column(
              children: <Widget>[
                _goodsName(index, context),
                _goodsPrice(index, context),
              ],
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    var scrollController = ScrollController();
    return Provide<ChildCategory>(
      builder: (context, child, childCategory) {
        try {
          if (Provide.value<ChildCategory>(context).page == 1) {
            scrollController.jumpTo(0.0);
          }
        } catch (e) {
          print('进入页面初始化:$e');
        }
        return Expanded(
          child: Container(
            width: ScreenUtil().setWidth(570),
            child: EasyRefresh(
              child: ListView.builder(
                controller: scrollController,
                itemBuilder: (context, index) {
                  return _listWidgetItem(index, context);
                },
                itemCount: Provide.value<ChildCategory>(context)
                    .categoryGoodsList
                    .length,
              ),
              footer: ClassicalFooter(
                  bgColor: Colors.white,
                  textColor: Colors.pink,
                  infoColor: Colors.pink,
                  showInfo: true,
                  noMoreText: '',
                  infoText: '刷新中',
                  loadText: '下拉刷新',
                  loadingText: '正在刷新',
                  loadedText: '刷新完成',
                  loadReadyText: '下拉刷新'),
              onLoad: () async {
                Provide.value<ChildCategory>(context).addPage();
                _getCategoryGoodsList(
                    Provide.value<ChildCategory>(context).page,
                    Provide.value<ChildCategory>(context).optId,
                    context);
              },
            ),
          ),
        );
      },
    );
  }
}
